package keeto.com.vn.classified.ui;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classified.config.IConstant;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.menutab.IMenuTabConfig;
import keeto.com.vn.classified.menutab.MenuTabAdapter;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.widgets.LogoutDialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
	private static String TAG = "LoginActivity";
	private EditText edtUsername, edtPass;
	private ImageButton btnBackHome;
	private Button btnLogin, btnRegister, btnForgetPass;
	private ImageButton btnBack;
	private ImageView imgSearch;
	private ProgressDialog mProgressDialog = null;
	public LoginListener mListener = new LoginListener();
	// state key
	private static final String STATE_KEY_USERNAME = "keeto.com.vn.classified.ui.UserName";
	private static final String STATE_KEY_PASSWORD = "keeto.com.vn.classified.ui.Password";
	private static String ACTION_LOGON_WITH_REGISTERED_INFO = "keeto.com.vn.classified.ui.LoginActivity.LogonAfaterRegistered";
	public static String ACTION_FILL_FIELD = "keeto.com.vn.classified.ui.LoginActivity.fill_fields";
	public static final String ACTION_LOGOUT = "keeto.com.vn.classified.ui.LoginActivity.LOGOUT";

	// extras
	public static String EXTRAS_USER_NAME = "UserName";
	public static String EXTRAS_PASSWORD = "Password";
	public static String EXTRAS_PRESENCE = "Presence";

	private Area mArea = null;

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		Log.i(TAG, "onNewIntent");
		setIntent(intent);
		String action = intent.getAction();
		Bundle extras = intent.getExtras();

		if (action != null) {
			if (action.equals(ACTION_LOGON_WITH_REGISTERED_INFO)) {
				if (extras != null) {
					String strUsername = extras.getString(EXTRAS_USER_NAME);
					String strPassword = extras.getString(EXTRAS_PASSWORD);

					edtUsername.setText(strUsername);
					edtPass.setText(strPassword);

					validateAccount();

				}
			} else if (action.equals(ACTION_FILL_FIELD)) {
				if (extras != null) {
					String strUsername = extras.getString(EXTRAS_USER_NAME);
					String strPassword = extras.getString(EXTRAS_PASSWORD);

					edtUsername.setText(strUsername);
					edtPass.setText(strPassword);

				}
			}
		}
	}

	@Override
	protected void onResume() {
		ClassifiedCore.getInstance(getApplication()).addListener(mListener);
		super.onResume();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		edtUsername.setText(savedInstanceState.getString(STATE_KEY_USERNAME));
		edtPass.setText(savedInstanceState.getString(STATE_KEY_PASSWORD));
	}

	@Override
	protected void onPause() {
		ClassifiedCore.getInstance(getApplication()).removeListener(mListener);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public static void actionLaunch(Context context) {
		Intent intent = new Intent(context, LoginActivity.class);
		context.startActivity(intent);
	}

	public static void actionLauchwithLogout(Context context) {
		Intent it = new Intent(context, LoginActivity.class);
		it.setAction(ACTION_LOGOUT);
		context.startActivity(it);
	}

	public static void actionLogonWithRegisteredInfo(Context context,
			String userName, String password) {
		Intent i = new Intent(context, LoginActivity.class);
		i.setAction(ACTION_LOGON_WITH_REGISTERED_INFO);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		i.putExtra(EXTRAS_USER_NAME, userName);
		i.putExtra(EXTRAS_PASSWORD, password);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		initUIComponent();
		onNewIntent(getIntent());
		mArea =  IAManager.getInstance(this).getMyArea();
	}

	public void initUIComponent() {
		edtUsername = (EditText) findViewById(R.id.edtUserName);
		edtPass = (EditText) findViewById(R.id.edtPassword);
		btnForgetPass = (Button) findViewById(R.id.btn_forgot_password);
		btnLogin = (Button) findViewById(R.id.btn_login);
		btnRegister = (Button) findViewById(R.id.btn_register);
		
		imgSearch=(ImageView)findViewById(R.id.btn_title_search_home);
		imgSearch.setVisibility(View.GONE);
		btnRegister.setOnClickListener(this);
		btnForgetPass.setOnClickListener(this);
		btnLogin.setOnClickListener(this);
		btnBackHome= (ImageButton) findViewById(R.id.btn_title_logo_home);
		btnBackHome.setOnClickListener(this);
		btnBack = (ImageButton)findViewById(R.id.btn_title_na_menu);
		btnBack.setOnClickListener(this);
		btnBack.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.icon_back));
		edtUsername.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (s != null && s.length() > 0
						&& edtUsername.getError() != null) {
					edtUsername.setError(null);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		edtPass.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (s != null && s.length() > 0 && edtPass.getError() != null) {
					edtPass.setError(null);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(STATE_KEY_USERNAME, edtUsername.getText().toString());
		outState.putString(STATE_KEY_PASSWORD, edtPass.getText().toString());
	}

	private void validateAccount() {

		if (edtUsername.getText().toString().equals("")) {

			setErrorMsg(
					getString(R.string.notice_enter_full_id,
							getString(R.string.app_name)), edtUsername);
			edtUsername.requestFocus();

			return;

		} else {
			if (edtPass.getText().toString().equals("")) {

				setErrorMsg(getString(R.string.notice_enter_your_password),
						edtPass);
				edtPass.requestFocus();

				return;
			}
		}

		// Pattern p = Pattern.compile("^[a-z0-9A-Z_]{6,20}$");
		// Matcher m1 = p.matcher(edtUsername.getText().toString());
		// boolean isMatch = m1.matches();
		//
		// if (!isMatch) {
		// setErrorMsg(getString(R.string.register_id_requirement),
		// edtUsername);
		// edtUsername.requestFocus();
		// return;
		// }

		ShowProgressDialog();
		ClassifiedCore.getInstance(getApplication()).taskLogon(mListener,
				edtUsername.getText().toString(), edtPass.getText().toString(),
				IConstant.ONLINE);

	}

	private void setErrorMsg(String msg, EditText viewId) {
		int ecolor = Color.RED; // whatever color you want
		String estring = msg;
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
		ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
		viewId.setError(ssbuilder);
	}

	public void DismissProgressDialog() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (mProgressDialog != null && mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();
				}
			}
		});
	}

	public void ShowProgressDialog() {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog
				.setMessage(getString(R.string.register_message_please_wait));
		mProgressDialog.setTitle(getString(R.string.validate_dialog_title));
		mProgressDialog.show();
	}

	class LoginListener extends ClassifiedListener {

		@Override
		public void finishLogon(final int returnCode) {
			super.finishLogon(returnCode);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						DismissProgressDialog();
						finish();
						// HomeClassifeldActivity.actionLaunch(LoginActivity.this);
					} else {
						Toast.makeText(LoginActivity.this,
								getString(R.string.text_login_failed),
								Toast.LENGTH_SHORT).show();
						DismissProgressDialog();
					}
				}
			});
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_forgot_password:
			ForgotPassActivity.actionLauch(LoginActivity.this);
			break;
		case R.id.btn_login:
			validateAccount();
			break;
		case R.id.btn_register:
			RegisterActivity.actionLaunch(LoginActivity.this);
			break;
		case R.id.btn_title_logo_home:
			HomeClassifeldActivity.actionLaunch(this);
			break;
		case R.id.btn_title_na_menu:
			LoginActivity.this.finish();
			break;

		default:
			break;
		}

	}

	class EventHandler extends Handler {

		public void SessionTimeOutDialog() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							LoginActivity.this);
					builder.setTitle(R.string.session_time_out_dialog_title);
					builder.setMessage(R.string.msg_connection_timeout);
					builder.setPositiveButton(
							R.string.session_time_out_dialog_network,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// switch to the Network Setting UI.
									Intent intent = new Intent(
											"android.settings.WIRELESS_SETTINGS");
									LoginActivity.this.startActivity(intent);
								}
							});

					builder.setNegativeButton(R.string.text_cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							});
					builder.create().show();
				}

			});
		}

	}
}
